<template>
    <a-modal class='addUserToGroupModal' 
        v-model:visible="visible" 
        :width="1100"
        title="新建组用户" 
        @ok="submit"
        @cancel="cancelAction"
        :ok-button-props="{ loading: __data.loading, disabled: __data.selectedRowKeys.length == 0 }">
        <div class="search-bar">
            <a-form 
            :label-col="{style: {width: '70px'}}"
            :wrapper-col="{style: {width: '120px'}}"
            layout="inline">
                <a-form-item label="用户名">
                    <a-input v-model:value="searchForm.username" allow-clear></a-input>
                </a-form-item>
                <a-form-item label="手机号">
                    <a-input v-model:value="searchForm.mobile" allow-clear></a-input>
                </a-form-item>
                <a-form-item label="机构名称">
                    <a-input v-model:value="searchForm.orgName" allow-clear></a-input>
                </a-form-item>
                <a-form-item label="用户类型">
                    <a-select v-model:value="searchForm.userType" allow-clear>
                        <a-select-option :value="1">SF同步用户</a-select-option>
                        <a-select-option :value="0">系统注册用户</a-select-option>
                    </a-select>
                </a-form-item>
            </a-form>
            <div style="float: right">
                <a-button type="primary" @click="searchAction" :loading="__data.loading" style="margin-right: 10px">查询</a-button>
                <a-button @click="resetAction" :loading="__data.loading">重置</a-button>
            </div>
        </div>
        <a-table
            :row-selection="{ selectedRowKeys: __data.selectedRowKeys ,onChange: onSelectChange }"
            :row-key="(record) => record.userId"
            :columns="__data.columns"
            :data-source="__data.tableData"
            :scroll="{ y: 500 }"
            :pagination="false"
            :loading="__data.loading"/>
        <a-pagination
            :current="__data.pg.current"
            :pageSize="__data.pg.pageSize"
            :total="__data.pg.total"
            :show-total="(total) => `共${total}条`"
            @change="onPageChange"
            @showSizeChange="onSizeChange"
            class='cus-pg'/>
    </a-modal>
</template>

<script lang='ts' setup>
    import { reactive, watch, toRefs, Ref, } from 'vue';
    import { addUesertoGroupReq, getUsersNotInCurrentGroupReq } from '/@/api/group';
    import { useMessage } from '/@/hooks/web/useMessage';
    import { Pagination as APagination, Modal as AModal, Table as ATable, Form as AForm, 
        FormItem as AFormItem, Select as ASelect, SelectOption as ASelectOption } from 'ant-design-vue';

    interface IEditInfo {
        groupId: number;
        userGroupModelList: Array<any>;
        [p:string]: any;
    }
    const { createMessage } = useMessage();
    const emit = defineEmits(['success', 'update:visible']);
    const props = defineProps({
        defaultData: {
            type: Object || undefined,
            default: () => undefined
        },
        visible: {
            type: Boolean,
            default: _ => false
        }
    })

    let __data = reactive({
        visible: false,
        loading: false,
        selectedRowKeys: [],
        columns: [
            {'title': '用户名', dataIndex: 'username', width: 90},
            {'title': '编号', dataIndex: 'userNo', width: 150},
            {'title': '邮箱', dataIndex: 'email', width: 150},
            {'title': '手机', dataIndex: 'mobile', width: 120},
            {'title': '机构', dataIndex: 'orgName', width: 150, customRender: ({record}) => record?.orgModel?.orgName},
            {'title': '用户类型', dataIndex: 'autoFlag', width: 150, customRender: ({record}) => record?.autoFlag == 1 ? '同步sf用户' : '系统注册用户'},
        ],
        pg: {
            current: 1,
            pageSize: 10,
            total: 0
        },
        tableData: []
    });
    const { defaultData, visible } = toRefs(props) as {
        defaultData: Ref<IEditInfo>,
        visible: Ref<boolean>
    };

    const getUserListAction = async function() {
        let p = {
            startIndex: __data.pg.current,
            pageSize: __data.pg.pageSize,
            username: searchForm.username,
            mobile: searchForm.mobile,
            orgName: searchForm.orgName,
            autoFlag: searchForm.userType,
            groupId: defaultData.value.groupId,
        };
        __data.loading = true;
        let { data, respCode, respMsg } = await getUsersNotInCurrentGroupReq(p);
        __data.loading = false;
        if (respCode === 200) {
            __data.tableData = data.list;
            __data.pg.total = data.total;
        } else {
            createMessage({
        message: respMsg,
        type: 'error'
      });
        }
    }
    const resetTableData = () => {
        __data.tableData = [];
        __data.pg.total = 0;
    }
    const resetTableSelect = () => {
        __data.selectedRowKeys = [];
    }
    watch(visible, (nv) => {
        if(nv) {
            resetAction();
            getUserListAction();
        }
    })


    const onSelectChange = (selectedRowKeys: []) => {
        __data.selectedRowKeys = selectedRowKeys;
    };

    const resetPg = () => {
        __data.pg.current = 1;
        __data.pg.pageSize = 10;
        __data.pg.total = 0;
    }
    const onPageChange = (n) => {
        __data.pg.current = n;
        getUserListAction();
    };
    const onSizeChange = (n: any) => {
        __data.pg.pageSize = n;
        __data.pg.current = 1;
        getUserListAction();
    };
    
    const submit = async () => {
        __data.loading = true;
        const { respCode, respMsg } = await addUesertoGroupReq({userIds: __data.selectedRowKeys, groupId: defaultData.value.groupId});
        __data.loading = false;
        if(respCode == 200) {
            visible.value = false;
            createMessage({
        message: respMsg,
      })
            emit('success')
            emit('update:visible', false)
        }
    };
    
    // search bar
    // 获取数据权限对应的应用
    const searchForm = reactive({
        username: '',
        mobile: '',
        orgName: '',
        userType: '',
    });
    const { resetFields } = AForm.useForm(searchForm, reactive({}))
    const searchAction = () => {
        resetPg();
        getUserListAction();
    }
    const resetAction = () => {
        resetFields();
        resetTableData();
        resetTableSelect();
        searchAction();
    }
    const cancelAction = () => {
        emit('update:visible', false)
    }

</script>

<style lang="less">
.addUserToGroupModal {
    .search-bar {
        display: flex;
        justify-content: space-between;
        margin-bottom: 15px;
    }
}
</style>